{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[-1.27769334  1.11414703  0.56194405 -0.91706935]\n",
      " [ 1.11414703 -2.6444184   0.74454762 -0.65349964]\n",
      " [ 0.56194405  0.74454762  0.04997731 -1.03090405]\n",
      " [-0.91706935 -0.65349964 -1.03090405  3.94811025]]\n",
      "\n",
      " Eigenvalues:\n",
      "[ 4.53597758 -3.31389346  0.09266001 -1.23876832]\n",
      "\n",
      " Eigenvectors:\n",
      "[[ 0.20003974  0.44893232 -0.33364643 -0.80444014]\n",
      " [ 0.14323051 -0.88556564 -0.27847394 -0.34309004]\n",
      " [ 0.26320184  0.11914803 -0.83042381  0.47636629]\n",
      " [-0.93284185 -0.00608435 -0.34860956 -0.09077689]]\n"
     ]
    }
   ],
   "source": [
    "dim = 4\n",
    "M = np.random.randn(dim, dim)\n",
    "M = M + M.T  # 对称化以保证本征分解存在; .T等价于.transpose(1,0)\n",
    "print(M)\n",
    "\n",
    "lm, u = np.linalg.eig(M)\n",
    "print('\\n Eigenvalues:')\n",
    "print(lm)\n",
    "\n",
    "print('\\n Eigenvectors:')\n",
    "print(u)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      " Check the orthogonality of U\n",
      "[[ 1.00000000e+00  1.38777878e-17  5.55111512e-17 -2.35922393e-16]\n",
      " [ 1.38777878e-17  1.00000000e+00 -5.55111512e-17 -1.17961196e-16]\n",
      " [ 5.55111512e-17 -5.55111512e-17  1.00000000e+00 -2.77555756e-17]\n",
      " [-2.35922393e-16 -1.17961196e-16 -2.77555756e-17  1.00000000e+00]]\n"
     ]
    }
   ],
   "source": [
    "print('\\n Check the orthogonality of U')\n",
    "print(u.dot(u.T))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      " The error of the eigenvalue decomposition = \n",
      "2.8037596640948706e-15\n"
     ]
    }
   ],
   "source": [
    "print('\\n The error of the eigenvalue decomposition = ')\n",
    "M1 = u.dot(np.diag(lm)).dot(u.T)\n",
    "err = np.linalg.norm(M - M1)\n",
    "print(err)\n",
    "\n",
    "# 练习：编写程序完成如下任务\n",
    "# 1. 验证u的每一列都是矩阵M的本征向量\n",
    "# 2. 验证U第n列给出的向量对应的本征值为lm的第n个元素"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
